using Digitalmes.Application.Scada.Models;
using Digitalmes.Application.Services;
using Digitalmes.Domain.Entities.Mes.Masters;
using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Scada.Services.Impl;

/// <summary>
/// 批次物料扫码服务。
/// </summary>
internal sealed class ScanBatchService(
    IRepository<ProdBatchMaterialLoading> batchMaterialLoadingRepo,
    IRepository<MdMaterial> materialRepo,
    IWorkstationQueryService workstationQueryService,
    IMaterialMatchService materialCheckService) : IScanBatchService
{
    public async Task<ScadaResult> ScanAsync(ScanBatchInput input, CancellationToken cancellationToken = default)
    {
        // 检索工位信息
        var workstation = await workstationQueryService.GetWorkstationAsync(input.LineCode, input.WsCode);
        if (workstation == null)
        {
            return ScadaResult.Error(ErrorCode.E1502);
        }

        // 找到定义的批次料信息
        // 批次料可以在任意时间上料，可以给多个产品使用，因此不能固定为属于某一个产品
        var matchFunc = await materialCheckService.GetMatchFuncAsync();
        var batchMaterials = await materialRepo.GetListAsync(m => m.Attr == MaterialAttrEnum.Batch, cancellationToken);
        var material = batchMaterials.FirstOrDefault(m => matchFunc(input.Barcode, m.Rules));
        if (material == null)
        {
            return ScadaResult.Error(ErrorCode.E1503);
        }

        // 新增记录
        ProdBatchMaterialLoading batchMaterialLoading = new()
        {
            LineId = workstation!.LineId,
            LineCode = workstation.Line?.LineCode,
            WorkstationId = workstation.Id,
            WorkstationCode = workstation.WsCode,
            MaterialId = material.Id,
            MaterialCode = material.Code,
            Barcode = input.Barcode,
            Qty = input.Qty,
            LoadingTime = DateTime.Now,
        };
        await batchMaterialLoadingRepo.InsertAsync(batchMaterialLoading, cancellationToken);

        return ScadaResult.Ok();
    }
}
